package analysis

import (
	"sync"
)

// 平均数计算器，用于计算平均数
type AverageCalculator struct {
	items             []float64
	total             float64
	average           float64
	index             int
	itemsActiveLength int
	itemsTotalLength  int
	mu                sync.RWMutex
}

func NewAverageCalculator(maxItems int) *AverageCalculator {
	return &AverageCalculator{itemsTotalLength: maxItems, items: make([]float64, maxItems)}
}

func (a *AverageCalculator) IsFull() bool {
	a.mu.RLock()
	defer a.mu.RUnlock()
	return a.itemsActiveLength == a.itemsTotalLength
}

func (a *AverageCalculator) LenItems() int {
	a.mu.RLock()
	defer a.mu.RUnlock()
	return a.itemsActiveLength
}

func (a *AverageCalculator) GetAverage() float64 {
	a.mu.RLock()
	defer a.mu.RUnlock()
	return a.average
}

func (a *AverageCalculator) Append(value float64) {
	a.mu.Lock()
	defer a.mu.Unlock()
	if a.itemsActiveLength < a.itemsTotalLength {
		a.items[a.index] = value
		a.index++
		a.itemsActiveLength++
	} else {
		if a.index >= a.itemsTotalLength {
			a.index = 0
		}
		pop := a.items[a.index]
		a.items[a.index] = value
		a.total -= pop
		a.index++
	}
	a.total += value
	a.average = a.total / float64(a.itemsActiveLength)
}
